package cn.com.zero.sample.user.service.impl;

import cn.com.zero.base.service.BaseService;
import cn.com.zero.sample.user.po.Session;
import cn.com.zero.sample.user.service.SessionService;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhoupeng
 * @version 1.0.0
 * @Description
 * @createTime 2022-07-14
 */
@Service
public class SessionServiceImpl extends BaseService implements SessionService {

    @NacosValue("${zero.session.duration: 0}")
    private long duration;
    /**
     * session 数据库
     */
    private Map<String, Session> sessionDB = new HashMap<>();

    @Override
    public String createSession(String username) {
        if (StrUtil.isEmpty(username)) {
            logger.warn("创建 session 失败，username 不能为空");
            return null;
        }

        removeSession(username);

        String sessionString = DigestUtils.md5DigestAsHex(String.format("%s%d", username, System.currentTimeMillis()).getBytes());
        sessionDB.put(sessionString, new Session(username, sessionString, System.currentTimeMillis()));
        return sessionString;
    }

    @Override
    public void removeSession(String username) {
        Session session = getSessionByUsername(username);
        if (session != null) {
            sessionDB.remove(session.getSession());
        }
    }

    @Override
    public boolean validSession(String session) {
        return false;
    }

    private Session getSessionByUsername(@NonNull String username) {
        for (Session session : sessionDB.values()) {
            if (StrUtil.equals(username, session.getUsername())) {
                return session;
            }
        }
        return null;
    }


    /**
     * 检测所有用户session合法性
     */
    public void checkAllSession() {
        if (duration > 0) {
            logger.info("执行session检测任务");
            long durationTimeMillis = duration * 1000;
            sessionDB.values().removeIf(session -> System.currentTimeMillis() - session.getCreatedTime() > durationTimeMillis);
        }
    }
}
